package org.rk.core.pubServer.service;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.rk.core.common.bean.OrderBean;
import org.rk.core.common.bean.PageData;
import org.rk.core.common.util.RKAlert;
import org.rk.core.common.util.RkObjectUtil;
import org.rk.core.jdbc.dao.IDBDao;
import org.rk.core.jdbc.dao.util.ParamMap;
import org.springframework.context.ApplicationEventPublisher;


public abstract class ModelService<T> implements IModelService<T> {
	
	private IDBDao<T> dbDao;
	private String pojoClassName;
	private Class<T> pojoClass;
	
	public ApplicationEventPublisher publisher;
	
	/**
	 * 用一个构造函数，初始化实例和泛型类基础，初始化当前线程超类的泛型类对象和名称
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ModelService(){
        this.pojoClass = null;
        try {
        	 Class c = getClass();
             Type t = c.getGenericSuperclass();
             if (t instanceof ParameterizedType) {
                 Type[] p = ((ParameterizedType) t).getActualTypeArguments();
                 this.pojoClass = (Class<T>) p[0];
                 
                 String pathPojoName=pojoClass.getName();
                 pojoClassName=pathPojoName.substring((pathPojoName.lastIndexOf(".")+1), pathPojoName.length());
             }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public Long insertModel(T model) {
		Long flag = null;
		try {
			flag=getDbDao().saveModelToId(model);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return flag;
	}
	@Override
	public boolean insertModelList(List<T> modelList){
		boolean flag=true;
		try {
			for(int i=0;i<modelList.size();i++){
				Long re=insertModel(modelList.get(i));
				if(RkObjectUtil.isEmpty(re)){
					flag=false;
					break;
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			flag=false;
		}
		return flag;
	}
	@Override
	public boolean deleteModel(T model) {
		return getDbDao().deleteModel(model);
	}
	@Override
	public Integer deleteBatchByParamMap(List<ParamMap> paramMapList) {
		return getDbDao().deleteByParamMap(getPojoClass(), paramMapList);
	}
	@Override
	public Integer deleteBatchByPro(String proName,Object proValue) {
		List<ParamMap> paramMapList = new ArrayList<ParamMap>();
		ParamMap pm = new ParamMap(proName, proValue);
		paramMapList.add(pm);
		return deleteBatchByParamMap(paramMapList);
	}
	@Override
	public boolean updateModel(T model) {
		return getDbDao().updateModel(model);
	}
	@Override
	public boolean updateModel(T model, String[] fileds) {
		return getDbDao().updateWithColumn(model,fileds);
	}
	@Override
	public T selectModel(String proName,Object proValue){
		if(RkObjectUtil.isEmpty(proValue)){
			return null;
		}
		 List<ParamMap> paramMapList=new ArrayList<ParamMap>();
		 ParamMap pm=new ParamMap(proName, proValue);
		 paramMapList.add(pm);
		 return getDbDao().queryForEntity(getPojoClass(), paramMapList);
	}
	@Override
	public T selectModel(Long id){
		if(RkObjectUtil.isEmpty(id)){
			RKAlert.Error("id不可以为空");
		}
		return selectModel("id",id);
	}
	@Override
	public List<T> selectModelList(Map<String, Object> mapObjs) {
		List<ParamMap> paramMapList=new ArrayList<ParamMap>();
		if(!RkObjectUtil.isEmpty(mapObjs)){
			for(Map.Entry<String, Object> entry :mapObjs.entrySet()){
				ParamMap pm=new ParamMap(entry.getKey(), entry.getValue());
				paramMapList.add(pm);
			}
		}
		try {
			List<T> result=getDbDao().queryForList(getPojoClass(), paramMapList);
			if(!RkObjectUtil.isEmpty(result) && result.size()>0){
				return result;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return Collections.emptyList();
	}
	@Override
	public List<T> selectModelList(Map<String, Object> mapObjs,List<OrderBean> orderList) {
		List<ParamMap> paramMapList=new ArrayList<ParamMap>();
		if(!RkObjectUtil.isEmpty(mapObjs)){
			for(Map.Entry<String, Object> entry :mapObjs.entrySet()){
				ParamMap pm=new ParamMap(entry.getKey(), entry.getValue());
				paramMapList.add(pm);
			}
		}
		paramMapList=ParamMap.addOrderToParamMap(paramMapList, orderList);
		try {
			List<T> result=getDbDao().queryForList(getPojoClass(), paramMapList);
			if(!RkObjectUtil.isEmpty(result)&&result.size()>0){
				return result;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return Collections.emptyList();
	}

	@Override
	public Integer batchDelete(T bean,String[] conditionFields){
		try {
			return getDbDao().deleteWithColumn(bean, conditionFields);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	@Override
	public List<T> selectModelListBySql(String sql) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public PageData selectModelListPage(Map<String, Object> mapObjs, PageData page) {
		List<ParamMap> paramMapList=new ArrayList<ParamMap>();
		for(Map.Entry<String, Object> entry :mapObjs.entrySet()){
			ParamMap pm=new ParamMap(entry.getKey(), entry.getValue());
			paramMapList.add(pm);
		}
		try {
			return getDbDao().queryToPage(getPojoClass(), paramMapList, page);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	@Override
	public PageData selectModelListPage(Map<String, Object> mapObjs, PageData page,List<OrderBean> orderList) {
		List<ParamMap> paramMapList=new ArrayList<ParamMap>();
		for(Map.Entry<String, Object> entry :mapObjs.entrySet()){
			ParamMap pm=new ParamMap(entry.getKey(), entry.getValue());
			paramMapList.add(pm);
		}
		paramMapList=ParamMap.addOrderToParamMap(paramMapList, orderList);
		try {
			return getDbDao().queryToPage(getPojoClass(), paramMapList, page);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	public IDBDao<T> getDbDao() {
		return dbDao;
	}

	public void setDbDao(IDBDao<T> dbDao) {
		this.dbDao = dbDao;
	}

	public String getPojoClassName() {
		return pojoClassName;
	}

	public void setPojoClassName(String pojoClassName) {
		this.pojoClassName = pojoClassName;
	}

	public Class<T> getPojoClass() {
		return pojoClass;
	}

	public void setPojoClass(Class<T> pojoClass) {
		this.pojoClass =pojoClass ;
	}
	
	public T getT() {  
        try {  
            return pojoClass.newInstance();  
        } catch (InstantiationException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (IllegalAccessException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        return null;  
    } 
	

}
